<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class User extends UserCommonController
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('MUser');
        $this->load->model('MUserAuthInfo');
        $this->temp_path = $this->config->item('tmp_path') ? trim($this->config->item('tmp_path'), '/ ') : 'upload/files';
    }

    public function fresh_user(){
        $this->ReturnJson(200,true,'获取成功',$this->user);
    }

    public function wx_bind(){
        if ($this->db->update('user',$this->param,['id' => $this->user->id])){
            $this->user = $this->MUser->getById($this->user->id);
            $this->ReturnJson(200,true,'绑定成功',$this->user);
        }else{
            $this->ReturnJson(1007,false,'更新失败',$this->user);
        }
    }

    /**
     * 接收提交个人认证的信息
     */
    public function auth_post(){
        //查询当前用户是否有认证记录
        $this->db->trans_start();
        $userAuthInfo = $this->MUserAuthInfo->getOne(['user_id'=>$this->user->id]);
        $updateInfo = $this->param;
        //更新user_auth_info
        if($userAuthInfo){
            $userAuthInfo->real_name = $updateInfo['real_name'];
            $userAuthInfo->id_num = $updateInfo['id_num'];
            $userAuthInfo->face_idcard = $updateInfo['face_idcard'];
            $userAuthInfo->back_idcard = $updateInfo['back_idcard'];
            $userAuthInfo->status = 1;  //有更新，状态就变为待审核
            $userAuthInfo->update_time = time();
            if(!$this->MUserAuthInfo->update($userAuthInfo)){
                $this->db->_trans_status = FALSE;
            }
        }else{
            $newInfo = $this->MUserAuthInfo->createVo();
            $newInfo->user_id = $this->user->id;
            $newInfo->real_name = $updateInfo['real_name'];
            $newInfo->id_num = $updateInfo['id_num'];
            $newInfo->face_idcard = $updateInfo['face_idcard'];
            $newInfo->back_idcard = $updateInfo['back_idcard'];
            $newInfo->status = 1;  //插入新，状态为待审核
            $newInfo->update_time = time();
            $newInfo->create_time = time();
            if(!$this->MUserAuthInfo->add($newInfo)){
                $this->db->_trans_status = FALSE;
            }
        }
        //更新user
        $this->user->auth_status = 1;   //user表中认证状态修改为已提交 待审核
        if(!$this->db->update('user',['auth_status'=>$this->user->auth_status],['id'=>$this->user->id])){
            $this->db->_trans_status = FALSE;
        }
        $this->db->trans_complete();
        if($this->db->trans_status() !== FALSE){
            $this->ReturnJson(200,true,'提交个人认证信息成功',$this->user,$this->param);
        }else{
            $this->ReturnJson(500,false,'提交个人认证信息失败',$this->user,$this->param);
        }
    }

    public function mobile_bind()
    {
        $this->load->library('WXBizDataCrypt',['appid' => IOSS_StaticConfig::$AppId, 'sessionKey' => $this->user->session_key,'wxBiz'],'wxBiz');
        $iv = $this->param['iv'];
        $encryptedData = $this->param['encryptedData'];
        $errCode = $this->wxBiz->decryptData($encryptedData, $iv, $data);
        if ($errCode !== 0) {
            $this->ReturnJson(1006, false, '非法数据',$errCode);
        }

        $this->user->mobile = $data['phoneNumber'];
        if ($this->db->update('user',['mobile' => $data['phoneNumber']],['id' => $this->user->id])){
            $this->ReturnJson(200, true, '绑定成功',$this->user);
        }else{
            $this->ReturnJson(1006, false, '绑定失败',$data);
        }
    }

    public function upload(){
        $field = $this->param['field'];
        if (!isset($_FILES) || !is_array($_FILES) || count($_FILES) < 1) {
            echo json_encode(Array('error' => '请选择要上传的文件！'));
            return;
        }
        $path = $this->temp_path . '/' . date('Y_m_d', time());
        if (!file_exists($path)){
            if (!mkdir($path, DIR_WRITE_MODE,true)) {
                echo json_encode(Array('error' => $path));
                return;
            }
        }
        //上传文件
        $config['upload_path'] = $path . '/';
        $config['allowed_types'] = 'jpg|png|bmp|swf|docx|doc|xls|xlsx|rar|zip';
        $config['max_size'] = '102400';
        $config['overwrite'] = FALSE;
        $this->load->library('upload', $config);
        $file_return = $this->upload->do_upload($field);
        if ($file_return) {
            $data = $this->upload->data();
            $message['path'] = $config['upload_path'] . $file_return;
            $message['url'] = site_url($message['path']);
            $message['file_size'] = $data['file_size'];
            $message['is_image'] = $data['is_image'];
            $success = true;
            $msg = '上传成功';
        } else {
            $success = false;
            $msg = $this->upload->display_errors('');
        }
        $this->ReturnJson(200,$success,$msg,$message);
    }

    public function pay(){
        $this->load->model('MOrder');
        $out_trade_no = uniqid(time());
        $type = $this->param['type'];
        switch ($type){
            case 'order':
                $order = $this->MOrder->getById($this->param['oid']);
                // 生成支付订单
                $wxPayOrder = [
                    'open_id' => $this->user->open_id,
                    'out_trade_no' => $out_trade_no,
                    'body' => $this->param['body'],
                    'total_fee' => $order->amount,
                    'user_id' => $this->user->id,
                    'oid' => $order->id,
                    'create_time' => time()
                ];
                if (!$this->db->insert('wx_pay',$wxPayOrder)){
                    $this->ReturnJson(500,false,'支付失败，请稍后重试',$wxPayOrder);
                };
                $config = [
                    'openId' => $this->user->open_id,
                    'out_trade_no' => $out_trade_no,
                    'body' => $this->param['body'],
                    'total_fee' => $order->amount * 100
                ];
                break;
            case 'promise':
                $order = $this->db->select('*')
                    ->from('user_promise')
                    ->where('id',$this->param['pid'])
                    ->get()
                    ->row();
                // 生成支付订单
                $wxPayOrder = [
                    'open_id' => $this->user->open_id,
                    'out_trade_no' => $out_trade_no,
                    'body' => $this->param['body'],
                    'total_fee' => $order->amount,
                    'user_id' => $this->user->id,
                    'pid' => $order->id,
                    'create_time' => time()
                ];
                if (!$this->db->insert('wx_pay',$wxPayOrder)){
                    $this->ReturnJson(500,false,'支付失败，请稍后重试',$wxPayOrder);
                };
                $config = [
                    'openId' => $this->user->open_id,
                    'out_trade_no' => $out_trade_no,
                    'body' => $this->param['body'],
                    'total_fee' => $order->amount * 100
                ];
                break;
        }

        $this->load->library('WxPay',$config);
        $pay = new WxPay($config);
        $this->ReturnJson(200,true,'获取成功',$pay->pay(),$this->param);
    }

    public function zc_times(){
        $times = $this->db->select('count(*) as num')
            ->from('order')
            ->where('user_id',$this->user->id)
            ->where('status',2)
            ->where('pay_status',1)
            ->get()
            ->row();
        $promise = $this->db->select('*')
            ->from('user_promise')
            ->where('user_id',$this->user->id)
            ->where('status <>',0)
            ->get()
            ->row();
        $data = array();
        $data['times'] = $times->num;
        $data['promise'] = $promise;
        $this->ReturnJson(200,true,'获取成功',$data);
    }
}
